<template>
  <div class="dashboard-panel">
    <div class="dashboard-header2">
      <span class="dashboard-title">WMS 出库量管理</span>
      <span class="dashboard-logo">WMS</span>
    </div>

    <!-- 日期选择器 -->
    <div class="date-filter">
      <div class="date-buttons">
        <el-button :type="selectedPeriod === 3 ? 'primary' : 'default'" @click="selectPeriod(3)" class="period-btn">
          未来3天
        </el-button>
        <el-button :type="selectedPeriod === 5 ? 'primary' : 'default'" @click="selectPeriod(5)" class="period-btn">
          未来5天
        </el-button>
        <el-button :type="selectedPeriod === 7 ? 'primary' : 'default'" @click="selectPeriod(7)" class="period-btn">
          未来一周
        </el-button>
      </div>
      <el-button type="primary" @click="fetchOutboundData" :loading="loading" class="query-btn">
        查询数据
      </el-button>
    </div>

    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">产品品类 <el-icon class="info-icon">
              <InfoFilled />
            </el-icon></div>
          <div class="stat-value">6 <span class="stat-unit">种</span></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">总出库数量 <el-icon class="info-icon">
              <InfoFilled />
            </el-icon></div>
          <div class="stat-value">{{ totalOutbound }} <span class="stat-unit">件</span></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">业务单据数量 <el-icon class="info-icon">
              <InfoFilled />
            </el-icon></div>
          <div class="stat-value">104 <span class="stat-unit">单</span></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-title">预测总出库数量 <el-icon class="info-icon">
              <InfoFilled />
            </el-icon></div>
          <div class="stat-value">{{ totalPredicted }} <span class="stat-unit">件</span></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div class="chart-title">已有出库量趋势</div>
          <v-chart :option="actualTrendOption" autoresize style="height:320px;" />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div class="chart-title">预测出库量 <el-icon class="info-icon">
              <InfoFilled />
            </el-icon></div>
          <v-chart :option="predictedTrendOption" autoresize style="height:320px;" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { InfoFilled } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import VChart from 'vue-echarts'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import axios from 'axios'
import http from '@/Axios/Htttp'

use([CanvasRenderer, LineChart, GridComponent, TooltipComponent, LegendComponent])

// 日期范围选择
const selectedPeriod = ref(3) // 默认选择3天
const dateRange = ref<[string, string]>(['', ''])

// 数据状态
const dateList = ref<string[]>([])
const actualOutboundQtyList = ref<number[]>([])
const predictedOutboundQtyList = ref<number[]>([])
const loading = ref(false)

// 计算总数
const totalOutbound = computed(() => {
  return actualOutboundQtyList.value.reduce((sum, val) => sum + (val || 0), 0).toLocaleString()
})

const totalPredicted = computed(() => {
  return predictedOutboundQtyList.value.reduce((sum, val) => sum + (val || 0), 0).toLocaleString()
})

// 选择时间段
const selectPeriod = (days: number) => {
  selectedPeriod.value = days
  const startDate = new Date()
  const endDate = new Date()
  endDate.setDate(startDate.getDate() + days)

  dateRange.value = [
    startDate.toISOString().split('T')[0],
    endDate.toISOString().split('T')[0]
  ]
}

// 格式化日期 - 添加年份
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
}

// 历史出库量趋势图配置
const actualTrendOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    formatter: (params: any) => {
      const param = params[0]
      return `${param.axisValue}<br/>出库数量: ${param.value || 0} 件`
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '10%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: dateList.value.map(formatDate),
    axisLabel: {
      rotate: 45,
      fontSize: 12
    }
  },
  yAxis: {
    type: 'value',
    name: '数量(件)',
    nameTextStyle: {
      fontSize: 12
    }
  },
  series: [{
    name: '历史出库数量',
    type: 'line',
    data: actualOutboundQtyList.value,
    itemStyle: { color: '#409EFF' },
    lineStyle: { color: '#409EFF', width: 2 },
    symbol: 'circle',
    symbolSize: 6,
    smooth: true,
    areaStyle: {
      color: {
        type: 'linear',
        x: 0, y: 0, x2: 0, y2: 1,
        colorStops: [
          { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
          { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
        ]
      }
    }
  }]
}))

// 预测出库量图配置 - 只显示预测数据
const predictedTrendOption = computed(() => {
  // 获取预测日期（从后端返回的日期列表中取最后几个日期）
  const predictedDates = dateList.value.slice(-predictedOutboundQtyList.value.length)

  // 计算数据范围，增加变化幅度
  const minValue = Math.min(...predictedOutboundQtyList.value.filter(v => v > 0))
  const maxValue = Math.max(...predictedOutboundQtyList.value)
  const range = maxValue - minValue
  const padding = range * 0.1 // 10% 的边距

  return {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const param = params[0]
        return `${param.axisValue}<br/>预测出库数量: ${param.value || 0} 件`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: predictedDates.map(formatDate),
      axisLabel: {
        rotate: 45,
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      name: '数量(件)',
      nameTextStyle: {
        fontSize: 12
      },
      min: Math.max(0, minValue - padding),
      max: maxValue + padding
    },
    series: [{
      name: '预测出库数量',
      type: 'line',
      data: predictedOutboundQtyList.value,
      itemStyle: { color: '#67c23a' },
      lineStyle: {
        color: '#67c23a',
        type: 'dashed',
        width: 3
      },
      symbol: 'triangle',
      symbolSize: 8,
      smooth: false,
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(103, 194, 58, 0.4)' },
            { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
          ]
        }
      }
    }]
  }
})

// 获取出库预测数据
const fetchOutboundData = async () => {
  loading.value = true
  try {
    const [startDate, endDate] = dateRange.value

    const response = await http.post('api/OutboundStatistics/GetOutboundPrediction', {
      startDate: new Date(startDate).toISOString(),
      endDate: new Date(endDate + 'T23:59:59').toISOString()
    })

    if (response.data) {
      dateList.value = response.data.dateList || []
      actualOutboundQtyList.value = response.data.actualOutboundQtyList || []
      predictedOutboundQtyList.value = response.data.predictedOutboundQtyList || []
    }
  } catch (error) {
    console.error('获取出库数据失败:', error)
    // 使用模拟数据作为fallback
    const mockDates = Array.from({ length: selectedPeriod.value }, (_, i) => {
      const date = new Date()
      date.setDate(date.getDate() + i)
      return date.toISOString().split('T')[0]
    })
    dateList.value = mockDates
    actualOutboundQtyList.value = Array.from({ length: selectedPeriod.value }, () => Math.floor(Math.random() * 200) + 100)
    predictedOutboundQtyList.value = Array.from({ length: selectedPeriod.value }, () => Math.floor(Math.random() * 200) + 120)
  } finally {
    loading.value = false
  }
}

// 初始化默认选择3天
onMounted(() => {
  selectPeriod(3)
  fetchOutboundData()
})
</script>

<style scoped>
.date-filter {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.date-buttons {
  display: flex;
  gap: 12px;
}

.period-btn {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.9);
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.period-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 255, 255, 0.3);
}

.period-btn.el-button--primary {
  background: linear-gradient(135deg, #409EFF 0%, #36a3f7 100%);
  border-color: #409EFF;
  color: white;
}

.query-btn {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 600;
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  transition: all 0.3s ease;
  min-width: 100px;
}

.query-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
}

.query-btn:active {
  transform: translateY(0);
}

.query-btn.is-loading {
  background: linear-gradient(135deg, #a0cfff 0%, #74b9ff 100%);
}

/* 添加装饰图标 */
.date-filter::before {
  content: "📊";
  font-size: 20px;
  margin-right: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .date-filter {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }

  .date-buttons {
    width: 100%;
    justify-content: center;
  }

  .period-btn {
    flex: 1;
    min-width: 80px;
  }

  .query-btn {
    width: 100%;
  }
}

.wms-layout {
  height: 100vh;
  background: #f5f7fa;
}

.wms-aside {
  background: #f5f7fa;
  border-right: 1px solid #e4e7ed;
  min-height: 100vh;
  overflow-y: auto;
}

.wms-main {
  padding: 0;
  background: #f8f9fa;
  min-height: 100vh;
}

.dashboard-panel {
  background: #fff;
  border-radius: 8px;
  margin: 24px;
  padding: 24px 24px 12px 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.dashboard-header2 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 18px;
  border-bottom: 2px solid #e4e7ed;
  padding-bottom: 10px;
}

.dashboard-title {
  color: #409EFF;
  font-size: 2.2rem;
  font-weight: bold;
}

.dashboard-logo {
  font-size: 2rem;
  color: #b3d8fd;
  font-weight: bold;
  letter-spacing: 2px;
}

.stat-card {
  margin-bottom: 18px;
  min-height: 110px;
}

.stat-title {
  font-size: 1.1rem;
  color: #333;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.info-icon {
  color: #67c23a;
  margin-left: 4px;
  font-size: 1rem;
}

.stat-value {
  color: #409EFF;
  font-size: 2.1rem;
  font-weight: bold;
  margin-top: 6px;
  display: inline-block;
}

.stat-unit {
  font-size: 1.1rem;
  color: #409EFF;
  margin-left: 2px;
}

.chart-card {
  min-height: 370px;
}

.chart-title {
  font-size: 1.1rem;
  color: #333;
  margin-bottom: 8px;
}
</style>
